﻿using SerialIoDemo.FixedHead;
using SerialIoDemo.FixedHead.ProtocolModel;
using System;
using System.IO.Ports;
using System.Windows.Forms;
using ZhCun.SerialIO;
using ZhCun.SerialIO.Utils;

namespace SerialIoDemo
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        void PrintLog(RichTextBox rtb, string log)
        {
            if (this.InvokeRequired)
            {
                Action<RichTextBox, string> act = PrintLog;
                rtb.Invoke(act, rtb, log);
            }
            else
            {
                rtb.AppendText($"[{DateTime.Now:HH:mm:ss.fff}] : {log}\r\n");
                //rtb.SelectionCharOffset
                rtb.Focus();
            }
        }

        ISerialServer SerialServer { set; get; }

        ISerialServer SerialClient { set; get; }

        /// <summary>
        /// 初始化上位机服务程序
        /// </summary>
        void InitServer()
        {
            SerialServer = new FDServer();
            SerialServer.ConnectChanged += (e) =>
            {
                PrintLog(rtbServerLog, $"{e.Server.Option.PortName} 状态：{e.Status}");
            };
            SerialServer.DataReadOver += (e) =>
            {
                //接收到的原始数据
                var hex = BytesTools.ByteArrToHex(e.Data, e.Offset, e.Count);
                PrintLog(rtbServerLogSrc, $"[R]: {hex}");
            };
            SerialServer.DataWriteOver += (e) =>
            {
                var hex = BytesTools.ByteArrToHex(e.Data, e.Offset, e.Count);
                PrintLog(rtbServerLogSrc, $"[W]: {hex}");
            };
        }

        /// <summary>
        /// 初始化下位机服务程序
        /// </summary>
        void InitClient()
        {
            SerialClient = new SerialServerBase();
            SerialClient.ConnectChanged += (e) =>
            {
                PrintLog(rtbClientLog, $"{e.Server.Option.PortName} 状态：{e.Status}");
            };
            SerialClient.DataReadOver += (e) =>
            {
                //接收到的原始数据
                var hex = BytesTools.ByteArrToHex(e.Data, e.Offset, e.Count);
                PrintLog(rtbClientLogSrc, $"[R]: {hex}");
            };
            SerialClient.DataWriteOver += (e) =>
            {
                var hex = BytesTools.ByteArrToHex(e.Data, e.Offset, e.Count);
                PrintLog(rtbClientLogSrc, $"[W]: {hex}");
            };
        }

        private void FrmMain_Load(object sender, EventArgs eee)
        {
            LogPrint.PrintHandle = (log) => PrintLog(rtbServerLog, log);

            var ports = SerialPort.GetPortNames();

            coBoxServerPort.Items.Clear();
            coBoxClientPort.Items.Clear();
            foreach (var item in ports)
            {
                coBoxServerPort.Items.Add(item);
                coBoxClientPort.Items.Add(item);
            }
            InitServer();
            InitClient();
        }

        private void btnServerStart_Click(object sender, EventArgs e)
        {
            if (btnServerStart.Text == "打开")
            {
                SerialServer.Start(coBoxServerPort.Text);
                btnServerStart.Text = "关闭";
            }
            else
            {
                SerialServer.Dispose();
                btnServerStart.Text = "打开";
            }
        }

        private void btnClientStart_Click(object sender, EventArgs e)
        {
            if (btnClientStart.Text == "打开")
            {
                SerialClient.Start(coBoxClientPort.Text);
                btnClientStart.Text = "关闭";
            }
            else
            {
                SerialClient.Dispose();
                btnClientStart.Text = "打开";
            }
        }

        private void btnWriteHex_Click(object sender, EventArgs e)
        {
            //16进制数据命令发送

            W_Hex w = new W_Hex();
            w.DevId = 5; //设备号
            w.Hex = txtData.Text; //16进制数据
            SerialClient.Write(w);
        }

        private void btnWriteText_Click(object sender, EventArgs e)
        {
            //[2字节固定头 0xaa,0xbb] [1字节 len] [1字节 cmd] [1字节 DevId] [N 字节 data] [2字节 crc 校验码]

            //字符串数据命令发送
            W_Text w = new W_Text();
            w.DevId = 6; //设备号
            w.Text = txtData.Text; //16进制数据
            SerialClient.Write(w);
        }

        private void btnSendSrc_Click(object sender, EventArgs e)
        {
            var data = BytesTools.HexToByteArr(txtSrcData.Text);
            SerialClient.Write(data);
        }
    }
}